﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fl_chart/fl_chart.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../widgets/fixed_header_with_tabs.dart';
import 'dart:ui' as ui;
import 'pressure_logic.dart';
import '../calendar/simple_calendar_view.dart';

class PressureView extends GetView<PressureLogic> {
  const PressureView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // 固定的头部（标题 + 日周月切换）
            Obx(() => FixedHeaderWithTabs(
                  title: '压力',
                  selectedIndex: _getSelectedIndex(),
                  onTabChanged: (index) {
                    switch (index) {
                      case 0:
                        controller.setTimeRange(PressureTimeRange.day);
                        break;
                      case 1:
                        controller.setTimeRange(PressureTimeRange.week);
                        break;
                      case 2:
                        controller.setTimeRange(PressureTimeRange.month);
                        break;
                    }
                  },
                  actions: [
                    IconButton(
                      icon: const Icon(Icons.stacked_bar_chart,
                          color: Colors.white),
                      onPressed: () {
                        Get.toNamed('/manual_measure',
                            arguments: {'type': 'pressure'});
                      },
                    ),
                    IconButton(
                      icon: const Icon(Icons.calendar_today,
                          color: Colors.white),
                      onPressed: () async {
                        final selectedDate = await Get.to(() =>
                            const SimpleCalendarView(
                                calendarType: CalendarType.pressure));
                        if (selectedDate != null && selectedDate is String) {
                          controller.loadDataByDate(selectedDate);
                        }
                      },
                    ),
                  ],
                )),
            // 可滚动的内容区域
            Expanded(
              child: SingleChildScrollView(
                child: Stack(
                  children: [
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      height: 240.h,
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.topRight,
                            end: Alignment.bottomRight,
                            colors: ThemeManager.to.backgroundGradientColors,
                            stops: const [0.1, 0.3, 0.7, 1.0],
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(16.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(height: 20.h),
                          _buildMainValue(),
                          SizedBox(height: 12.h),
                          _buildDateLine(),
                          SizedBox(height: 16.h),
                          _buildAreaChart(),
                          SizedBox(height: 24.h),
                          _buildManualMeasurementRecordsCard(), // 手动测量记录卡片（独立）
                          SizedBox(height: 16.h),
                          _buildRatioCard(),
                          SizedBox(height: 16.h),
                          _buildAboutCard(),
                          SizedBox(height: 40.h),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取当前选中的索引
  int _getSelectedIndex() {
    switch (controller.currentRange.value) {
      case PressureTimeRange.day:
        return 0;
      case PressureTimeRange.week:
        return 1;
      case PressureTimeRange.month:
        return 2;
    }
  }



  Widget _buildMainValue() {
    return Obx(() {
      final d = controller.data.value;
      final score = d?.score ?? 0;
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text('$score',
              style: TextStyle(
                  fontSize: 64.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white)),
        ],
      );
    });
  }

  Widget _buildDateLine() {
    final now = DateTime.now();
    const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    final w = weekdays[(now.weekday - 1).clamp(0, 6)];
    return Text(
        '${now.year}年${now.month.toString().padLeft(2, '0')}月${now.day.toString().padLeft(2, '0')}日，$w，00:00 平均',
        style: TextStyle(fontSize: 14.sp, color: Colors.grey[400]));
  }

  Widget _buildAreaChart() {
    return Obx(() {
      final d = controller.data.value;
      
      // 如果没有数据，显示空图表结构
      if (d == null) {
        return Column(
          children: [
            Container(
              height: 240.h,
              padding: EdgeInsets.all(12.w),
              decoration: BoxDecoration(
                color: const Color(0xff282528),
                borderRadius: BorderRadius.circular(20.r),
                border: Border.all(
                  color: const Color.fromRGBO(33, 33, 33, 1),
                  width: 1.0,
                ),
              ),
              child: Column(
                children: [
                  Expanded(
                    child: Center(
                      child: Text(
                        '暂无压力数据',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.grey[500],
                        ),
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: ['00:00', '06:00', '12:00', '18:00', '24:00']
                        .map((t) => Text(t,
                            style: TextStyle(
                                fontSize: 10.sp, color: Colors.grey[400])))
                        .toList(),
                  ),
                ],
              ),
            ),
            SizedBox(height: 16.h),
            _buildMeasureButton(),
          ],
        );
      }
      
      final list = d.hourly;
      final hasValidData = list.any((value) => value > 0);
      final selectedValue = 0.obs;
      final selectedTime = ''.obs;
      final touchPosition = Rxn<Offset>();

      return Column(
        children: [
          Container(
            height: 240.h,
            padding: EdgeInsets.all(12.w),
            decoration: BoxDecoration(
              color: const Color(0xff282528),
              borderRadius: BorderRadius.circular(20.r),
              border: Border.all(
                color: const Color.fromRGBO(33, 33, 33, 1),
                width: 1.0,
              ),
            ),
            child: Stack(
              children: [
                GestureDetector(
                  onPanStart: (details) {
                    if (!hasValidData) return;
                    _updateTouchPosition(details.localPosition, list, selectedValue, selectedTime, touchPosition);
                  },
                  onPanUpdate: (details) {
                    if (!hasValidData) return;
                    _updateTouchPosition(details.localPosition, list, selectedValue, selectedTime, touchPosition);
                  },
                  onPanEnd: (_) {
                    touchPosition.value = null;
                  },
                  child: CustomPaint(
                    painter: _PressureAreaPainter(
                      values: list,
                      touchPosition: touchPosition.value,
                    ),
                    child: Column(
                      children: [
                        Expanded(child: SizedBox.expand()),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: ['00:00', '06:00', '12:00', '18:00', '24:00']
                              .map((t) => Text(t,
                                  style: TextStyle(
                                      fontSize: 10.sp, color: Colors.grey[400])))
                              .toList(),
                        ),
                      ],
                    ),
                  ),
                ),
                // 触摸时显示数值
                Obx(() {
                  if (touchPosition.value == null) return const SizedBox.shrink();
                  return Positioned(
                    left: touchPosition.value!.dx - 40.w,
                    top: touchPosition.value!.dy - 40.h,
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                      decoration: BoxDecoration(
                        color: const Color(0xFFED5C2F),
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            '${selectedValue.value}',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                          Text(
                            selectedTime.value,
                            style: TextStyle(
                              fontSize: 10.sp,
                              color: Colors.white70,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                }),
                if (!hasValidData)
                  Center(
                    child: Text(
                      '暂无压力数据',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[500],
                      ),
                    ),
                  ),
              ],
            ),
          ),
          SizedBox(height: 16.h),
          _buildMeasureButton(),
        ],
      );
    });
  }

  void _updateTouchPosition(Offset position, List<int> values, RxInt selectedValue, RxString selectedTime, Rxn<Offset> touchPosition) {
    // 计算触摸位置对应的数据索引
    final chartWidth = 350.w; // 大约的图表宽度
    final stepX = chartWidth / values.length;
    final index = (position.dx / stepX).clamp(0, values.length - 1).toInt();
    
    if (values[index] > 0) {
      selectedValue.value = values[index];
      final hour = (index * 24 / values.length).floor();
      selectedTime.value = '${hour.toString().padLeft(2, '0')}:00';
      touchPosition.value = position;
    }
  }

  Widget _buildMeasureButton() {
    return Obx(() => GestureDetector(
          onTap: controller.isMeasuring.value
              ? null
              : controller.startPressureMeasurement,
          child: Container(
            width: double.infinity,
            height: 54.h,
            decoration: BoxDecoration(
              color: controller.isMeasuring.value
                  ? const Color(0xFF444444)
                  : const Color(0xFF151515),
              borderRadius: BorderRadius.circular(40.r),
              border: Border.all(
                color: const Color(0xFF444444),
                width: 1,
              ),
            ),
            child: Center(
              child: controller.isMeasuring.value
                  ? Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        SizedBox(
                          width: 20.w,
                          height: 20.w,
                          child: CircularProgressIndicator(
                            strokeWidth: 2.w,
                            valueColor: const AlwaysStoppedAnimation<Color>(
                                Colors.white),
                          ),
                        ),
                        SizedBox(width: 12.w),
                        Text(
                          '测量中...',
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    )
                  : Text(
                      '点击开始测量',
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
            ),
          ),
        ));
  }

  /// 构建手动测量记录卡片（独立卡片）
  Widget _buildManualMeasurementRecordsCard() {
    return Obx(() {
      final pressureData = controller.data.value;
      if (pressureData == null || pressureData.manualRecords.isEmpty) {
        return const SizedBox.shrink();
      }

      final isExpanded = false.obs;

      return Container(
        width: 335.w,
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: const Color(0xff282528),
          borderRadius: BorderRadius.circular(20.r),
          border: Border.all(
            color: const Color.fromRGBO(33, 33, 33, 1),
            width: 1.0,
          ),
        ),
        child: Obx(() => Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '当天测量记录 (${pressureData.manualRecords.length})',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w700,
                    color: Colors.white,
                  ),
                ),
                SizedBox(height: 12.h),
                // 虚线分隔
                CustomPaint(
                  size: Size(double.infinity, 1),
                  painter: _DashedLinePainter(),
                ),
                SizedBox(height: 12.h),
                GestureDetector(
                  onTap: () => isExpanded.value = !isExpanded.value,
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 8.h),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          isExpanded.value ? '收起' : '展开查看',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Icon(
                          isExpanded.value
                              ? Icons.keyboard_arrow_up
                              : Icons.keyboard_arrow_down,
                          color: Colors.grey[400],
                          size: 20.sp,
                        ),
                      ],
                    ),
                  ),
                ),
                if (isExpanded.value) ...[
                  SizedBox(height: 8.h),
                  ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: 200.h),
                    child: SingleChildScrollView(
                      child: Column(
                        children: pressureData.manualRecords.map((record) {
                          return Container(
                            margin: EdgeInsets.only(bottom: 8.h),
                            padding: EdgeInsets.symmetric(
                                horizontal: 12.w, vertical: 10.h),
                            decoration: BoxDecoration(
                              border: Border(
                                top: BorderSide(
                                  color: const Color(0xFF3A3A3A),
                                  width: 0.5,
                                ),
                                bottom: BorderSide(
                                  color: const Color(0xFF3A3A3A),
                                  width: 0.5,
                                ),
                              ),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  record.code,
                                  style: TextStyle(
                                    fontSize: 13.sp,
                                    color: Colors.grey[300],
                                  ),
                                ),
                                Text(
                                  '${record.value ?? 0}',
                                  style: TextStyle(
                                    fontSize: 13.sp,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ],
                            ),
                          );
                        }).toList(),
                      ),
                    ),
                  ),
                ],
              ],
            )),
      );
    });
  }

  Widget _buildRatioCard() {
    return Obx(() {
      final d = controller.data.value;
      final ratios = d?.ratios ?? [];

      // 定义颜色映射 - 按照设计图的顺序：放松、正常、中等、偏高
      final Map<String, Color> colorMap = {
        '放松': const Color(0xFF7DFFB3), // 浅绿色
        '正常': const Color(0xFF5FB878), // 深绿色
        '中等': const Color(0xFFFFB946), // 橙色
        '偏高': const Color(0xFFFF6B6B), // 红色
      };

      // 确保按照固定顺序显示
      final orderedLabels = ['放松', '正常', '中等', '偏高'];
      final orderedRatios = orderedLabels.map((label) {
        return ratios.firstWhere(
          (r) => r.info == label,
          orElse: () => PressureRatioData(info: label, value: 0),
        );
      }).toList();

      return Container(
        width: 358.w,
        height: 386.h,
        padding: EdgeInsets.all(24.w),
        decoration: BoxDecoration(
          color: const Color(0xff282528),
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '压力比例',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w700,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 32.h),
            // 环形图
            Center(
              child: SizedBox(
                width: 200.w,
                height: 200.w,
                child: ratios.isEmpty
                    ? Center(
                        child: Text(
                          '暂无数据',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.grey[500],
                          ),
                        ),
                      )
                    : PieChart(
                        PieChartData(
                          sectionsSpace: 8,
                          centerSpaceRadius: 60.w,
                          sections: orderedRatios.map((ratio) {
                            final color = colorMap[ratio.info] ?? Colors.grey;
                            return PieChartSectionData(
                              color: color,
                              value: ratio.value > 0 ? ratio.value.toDouble() : 0.1,
                              title: ratio.value > 0 ? '${ratio.value}%' : '',
                              radius: 35.w,
                              titleStyle: TextStyle(
                                fontSize: 14.sp,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            );
                          }).toList(),
                        ),
                      ),
              ),
            ),
            SizedBox(height: 32.h),
            // 图例和数值
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: orderedRatios.map((ratio) {
                final color = colorMap[ratio.info] ?? Colors.grey;
                return Column(
                  children: [
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          width: 12.w,
                          height: 12.w,
                          decoration: BoxDecoration(
                            color: color,
                            borderRadius: BorderRadius.circular(3.r),
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          ratio.info,
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      '${ratio.value}',
                      style: TextStyle(
                        fontSize: 32.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ],
                );
              }).toList(),
            ),
          ],
        ),
      );
    });
  }
}

  Widget _buildAboutCard() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color(0xff282528),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1.0,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('关于压力数据',
              style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w700,
                  color: Colors.green[300])),
          SizedBox(height: 8.h),
          Text('压力测量基于HRV等指标，用于评估身体整体应激水平。分为放松、正常、中等、偏高四级。',
              style: TextStyle(
                  fontSize: 13.sp, color: Colors.green[100], height: 1.5)),
        ],
      ),
    );
  }

class _PressureAreaPainter extends CustomPainter {
  final List<int> values;
  final Offset? touchPosition;
  
  _PressureAreaPainter({required this.values, this.touchPosition});

  @override
  void paint(Canvas canvas, Size size) {
    if (values.isEmpty) return;

    final w = size.width;
    final h = size.height - 20;
    final leftPadding = 30.0;
    final chartWidth = w - leftPadding;

    // 绘制Y轴刻度 (0, 50, 100)
    _drawYAxisLabels(canvas, h, leftPadding);

    // 过滤出有效数据点
    final validValues = values.where((v) => v > 0).toList();
    if (validValues.isEmpty) {
      _drawBaseline(canvas, size, leftPadding);
      return;
    }

    final minV = validValues.reduce((a, b) => a < b ? a : b);
    final maxV = validValues.reduce((a, b) => a > b ? a : b);
    final range = (maxV - minV).clamp(1, 100).toDouble();
    final stepX = chartWidth / values.length;

    // 收集所有有效的数据点
    final List<Offset> points = [];
    double x = leftPadding + stepX / 2;
    
    for (int i = 0; i < values.length; i++) {
      final value = values[i];
      if (value > 0) {
        final y = h - ((value - minV) / range) * h * 0.8;
        points.add(Offset(x, y));
      }
      x += stepX;
    }

    if (points.isEmpty) {
      _drawBaseline(canvas, size, leftPadding);
      return;
    }

    // 找到最低点的Y坐标
    final lowestY = points.map((p) => p.dy).reduce((a, b) => a > b ? a : b);

    // 创建平滑曲线路径
    final path = Path();
    final area = Path();
    
    path.moveTo(points[0].dx, points[0].dy);
    area.moveTo(points[0].dx, lowestY);
    area.lineTo(points[0].dx, points[0].dy);

    // 使用三次贝塞尔曲线绘制平滑曲线
    for (int i = 0; i < points.length - 1; i++) {
      final p0 = i > 0 ? points[i - 1] : points[i];
      final p1 = points[i];
      final p2 = points[i + 1];
      final p3 = i < points.length - 2 ? points[i + 2] : p2;

      // 计算控制点
      final cp1x = p1.dx + (p2.dx - p0.dx) / 6;
      final cp1y = p1.dy + (p2.dy - p0.dy) / 6;
      final cp2x = p2.dx - (p3.dx - p1.dx) / 6;
      final cp2y = p2.dy - (p3.dy - p1.dy) / 6;

      path.cubicTo(cp1x, cp1y, cp2x, cp2y, p2.dx, p2.dy);
      area.cubicTo(cp1x, cp1y, cp2x, cp2y, p2.dx, p2.dy);
    }

    area.lineTo(points.last.dx, lowestY);
    area.close();

    // 从最低点开始的渐变
    final fillPaint = Paint()
      ..shader = LinearGradient(
        begin: Alignment.topCenter,
        end: Alignment.bottomCenter,
        colors: [
          const Color(0xFFED5C2F).withValues(alpha: 0.4),
          const Color(0xFFED5C2F).withValues(alpha: 0.05)
        ],
      ).createShader(Rect.fromLTWH(leftPadding, 0, chartWidth, h))
      ..style = PaintingStyle.fill;

    final linePaint = Paint()
      ..color = const Color(0xFFED5C2F)
      ..strokeWidth = 2
      ..style = PaintingStyle.stroke;

    canvas.drawPath(area, fillPaint);
    canvas.drawPath(path, linePaint);

    // 绘制触摸指示器
    if (touchPosition != null) {
      _drawTouchIndicator(canvas, touchPosition!, h);
    }
  }

  void _drawYAxisLabels(Canvas canvas, double height, double leftPadding) {
    final textStyle = TextStyle(
      color: Colors.grey[600],
      fontSize: 10,
    );

    final labels = ['100', '50', '0'];
    final positions = [0.0, height * 0.5, height];

    for (int i = 0; i < labels.length; i++) {
      final textSpan = TextSpan(text: labels[i], style: textStyle);
      final textPainter = TextPainter(
        text: textSpan,
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      textPainter.paint(
        canvas,
        Offset(0, positions[i] - textPainter.height / 2),
      );

      // 绘制水平参考线
      final linePaint = Paint()
        ..color = Colors.grey.withValues(alpha: 0.2)
        ..strokeWidth = 0.5;
      canvas.drawLine(
        Offset(leftPadding, positions[i]),
        Offset(leftPadding + 320, positions[i]),
        linePaint,
      );
    }
  }

  void _drawTouchIndicator(Canvas canvas, Offset position, double height) {
    final paint = Paint()
      ..color = const Color(0xFFED5C2F)
      ..style = PaintingStyle.fill;

    // 绘制触摸点
    canvas.drawCircle(position, 6, paint);
    
    // 绘制垂直线
    final linePaint = Paint()
      ..color = const Color(0xFFED5C2F).withValues(alpha: 0.5)
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;
    
    canvas.drawLine(
      Offset(position.dx, 0),
      Offset(position.dx, height),
      linePaint,
    );
  }

  void _drawBaseline(Canvas canvas, Size size, double leftPadding) {
    final w = size.width;
    final h = size.height - 20;
    final baselineY = h * 0.9;

    final paint = Paint()
      ..color = Colors.grey.withValues(alpha: 0.5)
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;

    canvas.drawLine(Offset(leftPadding, baselineY), Offset(w, baselineY), paint);
  }

  @override
  bool shouldRepaint(covariant _PressureAreaPainter oldDelegate) {
    return oldDelegate.touchPosition != touchPosition ||
        oldDelegate.values != values;
  }
}

class _DashedLinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = const Color(0xFF3A3A3A)
      ..strokeWidth = 0.5
      ..style = PaintingStyle.stroke;

    const dashWidth = 3.0;
    const dashSpace = 3.0;
    double startX = 0;

    while (startX < size.width) {
      canvas.drawLine(
        Offset(startX, 0),
        Offset(startX + dashWidth, 0),
        paint,
      );
      startX += dashWidth + dashSpace;
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
